package com.dlshouwen.os.validator.controller;

import java.util.List;
import java.util.ResourceBundle;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 演示
 * @author 大连首闻科技有限公司
 * @version 1.0
 */
@Controller
@SuppressWarnings({"unchecked", "deprecation"})
@RequestMapping("/unique")
public class UniqueController {
	
	private JdbcTemplate jdbcTemplate;
	
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	@Resource(name="defaultJdbcTemplate")
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	/**
	 * 执行唯一验证
	 * @throws Exception
	 */
	@RequestMapping(value="", method=RequestMethod.POST)
	public void unique(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		获取参数
		String validParams = request.getParameter("validParams");
		JSONObject validParamsObj = JSONObject.fromObject(validParams);
		String sqlCode = validParamsObj.getString("sqlCode");
		String key = validParamsObj.getString("key");
		List<Object> attrs = (List<Object>)JSONArray.toCollection(validParamsObj.getJSONArray("attrs"), List.class);
//		获取sql
		ResourceBundle bundle = ResourceBundle.getBundle("UniqueSqls");
		String sql = bundle.getString(sqlCode);
//		获取参数列表
		int count;
		if(attrs==null||attrs.size()==0){
			count = jdbcTemplate.queryForInt(sql, key);
		}else{
			attrs.add(0, key);
			count = jdbcTemplate.queryForObject(sql, attrs.toArray(), Integer.class);
		}
//		回写数据
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(String.valueOf(count==0?true:false));
	}
	
}